package com.yincb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.SQLException;

@Component
public class EmpDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public void save(Emp emp){
        String sql = "insert into emp(empno,ename) values(?,?)";
        int update = jdbcTemplate.update(sql, emp.getEmpno(), emp.getEname());
        System.out.println(update);
    }


    public void update(Emp emp){
        Connection connection = null;
        try {
            connection.setAutoCommit(false);
            connection = jdbcTemplate.getDataSource().getConnection();
            String sql = "UPDATE emp SET ename = ? WHERE empno = ?";
            int update = jdbcTemplate.update(sql, emp.getEname(), emp.getEmpno());
            System.out.println(update);
            int a = 1/0;
            connection.commit();
        } catch (Exception throwables) {
            try {
                connection.rollback();
                throwables.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Transactional
    public void updateByAnnotation(Emp emp){
        try {
            String sql = "UPDATE emp SET ename = ? WHERE empno = ?";
            int update = jdbcTemplate.update(sql, emp.getEname(), emp.getEmpno());
            System.out.println(update);
            int a = 1/0;
        } catch (Exception throwables) {
            throw new RuntimeException("0001");
        }
    }

}
